package com.chhuang.huaao.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONObject;
import com.chhuang.huaao.controller.AdminController;
import com.chhuang.huaao.controller.ClientController;
import com.chhuang.huaao.thread.TokenFileThread;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;

/**
 * 清理超过30天未登录系统的token
 * 
 * @author CHHUANG
 *
 */
public class AppLoginTokenClearTask {
	
	private static final Log log = LogFactory.getLog(AppLoginTokenClearTask.class);
	
	/**
	 * 过期天数
	 */
	public static final Long OVERDUE = 30l;

	public void execute() {
		long now = System.currentTimeMillis();

		//遍历客户APP的token
		List<String> keys = new ArrayList<String>();
		for (Map.Entry<String, JSONObject> entry : ClientController.tokens.entrySet()) {
			JSONObject token = entry.getValue();
			if(token==null){//不存在
				keys.add(entry.getKey());
			}else{
				long time = token.getLong(SysConstants.Token.TIME);
				if(now-time > OVERDUE*86400000l){//过期
					keys.add(entry.getKey());
				}
			}
		}
		if(Assert.isValidCollection(keys)){
			for(String key : keys){
				ClientController.tokens.remove(key);
				//把token写入文件
				new Thread(new TokenFileThread(ClientController.tokens, SysConfig.getValue(SysConstants.Config.CLIENT_TOKEN_PATH))).start();
				log.debug("客户登录过期key为："+key);
			}
		}
		
		//遍历管理员APP的token
		keys = new ArrayList<String>();
		for (Map.Entry<String, JSONObject> entry : AdminController.tokens.entrySet()) {
			JSONObject token = entry.getValue();
			if(token==null){//不存在
				keys.add(entry.getKey());
			}else{
				long time = token.getLong(SysConstants.Token.TIME);
				if(now-time > OVERDUE*86400000l){//过期
					keys.add(entry.getKey());
				}
			}
		}
		if(Assert.isValidCollection(keys)){
			for(String key : keys){
				AdminController.tokens.remove(key);
				//把token写入文件
				new Thread(new TokenFileThread(AdminController.tokens, SysConfig.getValue(SysConstants.Config.ADMIN_TOKEN_PATH))).start();
				log.debug("管理员登录过期key为："+key);
			}
		}
	}
	
}
